package com.imay.live.helper;

import android.app.Activity;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.helper.ActivityHelper;
import com.imay.live.Constants;
import com.imay.live.R;
import com.imay.live.activity.MarketActivity;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.RoomLiveNormalActivity;
import com.imay.live.activity.RoomLiveShortActivity;
import com.imay.live.activity.RoomPushNormalActivity;
import com.imay.live.activity.RoomPushShortActivity;
import com.imay.live.activity.WebViewActivity;
import com.imay.live.activity.authentication.AuthenticationActivity;
import com.imay.live.activity.authentication.UserSignActivity;
import com.imay.live.activity.discovery.DynamicActivity;
import com.imay.live.activity.discovery.SupperDekaronActivity;
import com.imay.live.activity.dynamics.LabelFeedsActivity;
import com.imay.live.activity.load.StartActivity;
import com.imay.live.activity.profit.IncomeActivity;
import com.imay.live.activity.recharge.RechargeActivity;
import com.imay.live.activity.user.ResigterActivity;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.TopicModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.dialog.ShareDialogFragment;

import java.net.URLDecoder;
import java.util.HashMap;


/**
 * H5回调到主应用的跳转至对应的分享详情页面
 * Created by chan on 2017/4/28.
 */

public class H5Helper {

    // Intent传递参数
    public final static String H5REDIRECTION_KEY = "h5redirection_key";
    public final static String H5SCHEME = "imay";
    public final static String H5HOST = "com.imay.live";

    public static boolean isAppSchemeUri(Uri uri) {
        try {
            if (uri != null) {
                String scheme = uri.getScheme();
                String host = uri.getHost();
                return (UrlHelper.SCHEME.equals(scheme) && UrlHelper.HOST.equals(host) || (H5SCHEME.equals(scheme) && H5HOST.equals(host)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 解析
     *
     * @param queryStr
     * @return
     */
    private static HashMap<String, String> getH5QueryMap(String queryStr) {
        if (queryStr.contains("&")) {
            String[] querys = queryStr.split("&");
            if (querys.length > 0) {
                HashMap<String, String> map = new HashMap<>();
                for (String str : querys) {
                    if (str.contains("=")) {
                        String[] strs = str.split("=");
                        map.put(strs[0], strs[1]);
                    }
                }
                return map;
            }
        }
        return null;
    }


    /**
     * 判断后台应用是否被清掉，如果没清掉，从LoadActivity拦截到数据后，查看栈顶第二个Activity进行跳转并调至H5分享详情页面
     *
     * @param queryStr
     * @return
     */
    public static boolean startActivity(String queryStr) {
        Activity activity = ActivityHelper.getInstance().getH5ReBackActivity();
        if (activity != null && !(activity instanceof StartActivity)) {
            if (AccountManager.getInstance().isLogined()) {
                if (!TextUtils.isEmpty(queryStr)) {//重复打开时候
                    startActivity(queryStr, activity);
                }
                return true;//一定需要TRUE
            } else {
                return true;
            }
        }
        return false;
    }

    public static boolean startActivity(String url, Activity activity) {
        return startActivity(url, activity, null);
    }

    /**
     * H5打开页面
     *
     * @param url
     * @param activity
     */
    public static boolean startActivity(String url, Activity activity, String titleText) {
        /**
         * type 1: 直播间   2：其他用户个人中心  3：动态详情  9：话题页
         */
        boolean result = false;
        if (!TextUtils.isEmpty(url)) {
            url = url.trim();
            Uri uri;
            try {
                uri = Uri.parse(url);
            } catch (Exception e) {
                return false;
            }
            String type = uri.getQueryParameter("type");
            if (type != null) {
                switch (type) {
                    case "1": // 直播间
                        String roomId = uri.getQueryParameter("roomId");
//                String roomurl = uri.getQueryParameter("url");
                        try {
                            getRoonInfo(Long.valueOf(roomId), activity);
                            result = true;
                        } catch (Exception e) {
                        }
//                        String roomId = map.get("roomId");
//                        String url = map.get("url");
//                        if (TextUtils.isEmpty(roomId) || TextUtils.isEmpty(url)) {
//                            ToastUtil.show(activity.getApplicationContext(), R.string.str_label_share_errer);
//                            break;
//                        }
//
//                        /**
//                         * 跳转前界面是直播间时，不用再跳转
//                         */
//                        if (activity instanceof LiveActivity) {
//
//                        }

                        break;
                    case "2": // 个人页面
                        String uid = uri.getQueryParameter("uid");
                        try {
                            int ui = Integer.valueOf(uid);
                            ProfileActivity.start(activity, ui);
                            webfinish(activity);
                            result = true;
                        } catch (Exception e) {
                        }
                        break;
                    case "3": // 动态详情
                        String FeedId = uri.getQueryParameter("FeedId");
                        try {
                            int id = Integer.valueOf(FeedId);
                            DynamicActivity.start(activity, id, activity.getString(R.string.str_imay_photo));
                            webfinish(activity);
                            result = true;
                        } catch (Exception e) {
                        }
                        break;
                    case "4": {
                        RechargeActivity.start(activity);
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "5": {
                        RoomPushNormalActivity.startActivity(activity);
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "6": {
                        MediaHelper.startPhoto(activity, Constants.REQUEST_PICK_IMAGE);
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "7": {
                        MediaHelper.startRecord(activity);
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "8": {
                        String title = uri.getQueryParameter("title");
                        String text = uri.getQueryParameter("text");
                        String imageUrl = uri.getQueryParameter("imageUrl");
                        String shareurl = uri.getQueryParameter("url");
                        if (activity instanceof AppCompatActivity) {
                            DialogFragmentHelper.showDialogFragment(((AppCompatActivity) activity).getSupportFragmentManager(), ShareDialogFragment.newInstance(ShareDialogFragment.WEB, shareurl, title, text, imageUrl, null));
                            result = true;
                        }
                        break;
                    }
                    case "9": // 话题界面
                        String LabelContent = uri.getQueryParameter("LabelContent");
                        if (!TextUtils.isEmpty(LabelContent)) {
                            LabelFeedsActivity.startActivity(activity, URLDecoder.decode(LabelContent));
                            webfinish(activity);
                            result = true;
                        }
                        break;
                    case "10": {
                        //MainActivity2.startActivity(activity, url);
                        MarketActivity.start(activity, 0);
                        result = true;
                        break;
                    }
                    case "11": // 手机绑定
                        ResigterActivity.startForResult(activity, IncomeActivity.RECODE, ResigterActivity.STATUS_BIND_PHONE);
                        result = true;
                        break;
                    case "12": {
                        AuthenticationActivity.startForResult(activity, IncomeActivity.RECARDCODE);
                        result = true;
                        break;
                    }
                    case "13": {//商城指定座驾 暂时未实现
                        String equiqId = uri.getQueryParameter("equiqId");
                        try {
                            int id = Integer.valueOf(equiqId);
                            MarketActivity.start(activity, id);
                            webfinish(activity);
                            result = true;
                        } catch (Exception e) {
                        }
                        break;
                    }
                    case "14": {//活动H5
                        String tupurl = uri.getQueryParameter("url");
                        WebViewActivity.startActivity(activity, titleText, getUrlWithParams(tupurl));
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "15": {//挑战准备页面
                        RoomPushShortActivity.startActivity(activity);
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "16": {//观看视频&直播页面imay://com.imay.live/openwith?type=16&shortLiveId=356
                        String shortLiveId = uri.getQueryParameter("nextShortLiveId");
                        if (!TextUtils.isEmpty(shortLiveId)) {
                            try {
                                long id = Long.valueOf(shortLiveId);
                                RoomLiveShortActivity.startLiveActivity(activity, id,false);//暂时屏蔽 固定ID
                                webfinish(activity);
                                result = true;
                                break;
                            } catch (Exception e) {

                            }
                        }
                        RoomLiveShortActivity.startActivity(activity);
                        webfinish(activity);
                        result = true;
                    }
                    break;
                    case "17": {//签约
                        UserSignActivity.startActivity(activity);
                        webfinish(activity);
                        result = true;
                        break;
                    }
                    case "18": {//imay://com.imay.live/openwith?type=18&topicId=XXX
                        String topicID = uri.getQueryParameter("topicId");
                        if (!TextUtils.isEmpty(topicID)) {
                            try {
                                long id = Long.valueOf(topicID);
                                getTopicModel(id, activity);
                                result = true;
                            } catch (Exception e) {

                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        }
        return result;
    }

    private static void webfinish(Activity activity) {
        if (activity instanceof WebViewActivity) {
//            activity.finish();//产品跟测试要求去掉关闭
        }
    }

    private static void getRoonInfo(long roomId, final Activity activity) {
        ProtoRequestHelper.task(ProtoHttpFactory.getRoomInfo(roomId)).setTag(activity.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<RoomInfoModel> result = JSON.parseObject(data, new TypeReference<Result<RoomInfoModel>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        RoomLiveNormalActivity.startActivity(activity, result.data);
                        webfinish(activity);

                    }

                } catch (Exception e) {
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
            }
        });
    }

    private static void getTopicModel(long topicId, final Activity activity) {
        ProtoRequestHelper.task(ProtoHttpFactory.getTopic(topicId)).setTag(activity.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<TopicModel> result = JSON.parseObject(data, new TypeReference<Result<TopicModel>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        SupperDekaronActivity.start(activity, result.data);
                        webfinish(activity);
                    }

                } catch (Exception e) {
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
            }
        });
    }

    private static String getUrlWithParams(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        StringBuffer buffer = new StringBuffer(url);
        buffer.append("?uid=");
        buffer.append(AccountManager.getInstance().getUid());
        buffer.append("&accessToken=");
        buffer.append(AccountManager.getInstance().getAccessCode());
        return buffer.toString();
    }
}
